import axios from 'axios'

const instance = axios.create({
	timeout: 30000,
	baseURL: '',
})
axios.defaults.headers.post['Content-Type'] = 'application/json;utf-8'
// 请求拦截器
instance.interceptors.request.use(
	(config) => {
		if (config.method === 'formdata') {
			config.headers.post['Content-Type'] =
				'multipart/form-data;charset=utf-8'
			config.method = 'post'
			// 兼容某些老接口的入参需要特殊的入参处理(.eg: AddMyOption)
			const fPar =
				config.otherPar == 'useSearch'
					? new URLSearchParams()
					: new FormData()
			for (const key in config.params) {
				fPar.append(key, config.params[key])
			}
			config.data = fPar
			config.params = ''
		} else if (config.method === 'query') {
			config.method = 'post'
			config.data = ''
		} else if (config.method === 'post') {
			config.data = config.params
			config.params = ''
		}
		config.headers['Cache-Control'] = 'no-cache'
		// 本地环境调试需要手动添加bjwt请求头
		if (process.env.NODE_ENV === 'dev') {
			config.headers['bjwt'] = localStorage.getItem('bjwt')
		}
		// 本地化uparms参数signet请求头
		const signet =
			bjsdk.query('signet') ||
			localStorage.getItem('signet') ||
			sessionStorage.getItem('signet')
		signet && (config.headers['signet'] = signet)
		// 增加渠道和端请求头
		config.headers['channel'] = bjsdk.isWX ? 'WEIXIN' : 'QIWEI'
		config.headers['clientType'] = bjsdk.isMobile ? 'MOBILE' : 'PC'
		return config
	},
	(err) => {
		return Promise.reject(err)
	}
)

//响应拦截器
instance.interceptors.response.use(
	(res) => {
		if (res.status === 200) {
			return res.data
		}
		return addErrorLog(res.data)
	},
	(err) => {
		return addErrorLog(err)
	}
)
const addErrorLog = (res) => Promise.reject(res)
const $axios = (option) => {
	const parDef = {
		url: '',
		data: {},
		method: 'post',
		headers: {},
	}
	const par = Object.assign(parDef, option)
	return new Promise((resolve, reject) => {
		instance({
			url: par.url,
			params: par.data,
			method: par.method,
			headers: par.headers,
		})
			.then((res) => resolve(res))
			.catch((err) => reject(err))
	})
}

/**
 *
 * @param {*} url --api路径
 * @param {*} data -- 请求参数 json对象
 * @param {*} method --请求方式：get/post/formdata
 */
export const getData = (url = '', data = {}, method = 'post', headers = {}) => {
	if (method === 'get') {
		const hashReg = /#[^#]+$/
		const [hash] = url.match(hashReg) || []
		if (hash) {
			url = url.replace(hashReg, '')
			if (Object.keys(data).length) {
				url += Object.entries(data).reduce(
					(total, [key, val]) => `${total}&${key}=${val}`,
					'?'
				)
				url += hash
				data = {}
			}
		}
	}
	return $axios({
		url,
		method,
		data,
		headers,
	})
}
